package com.hevery.web.controller;

import com.hevery.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: zhy
 * @description:
 * @date: Created on 2017/10/15
 * @modified By:
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private String folder = "G:\\Spring_Boot_Web\\spring-security\\hevery-security-demo\\src\\main\\java\\com\\hevery\\web\\controller";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        /**第一个参数：文件夹，第二个参数：文件名*/
        File localFile = new File(folder,System.currentTimeMillis()+".txt");
        /**把file写到localFile*/
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    /**使用jdk1.7的try-with-resource语法*/
    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception{
        try(InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
            OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/x-download");
            /**定义下载的时候的文件名*/
            response.setHeader("Content-Disposition","attachment;filename=test.txt");
            /**常用的用来处理IO的工具，需要引入依赖*/
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
